package cn.edu.klmy.controller;

import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import web.models.CommonResult;
import cn.edu.klmy.dao.IAuthenticationDao;
import cn.edu.klmy.models.user.AuthenticationUser;
import cn.edu.klmy.spring.security.core.userdetails.CourseSystemUser;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;

/**
 * 认证及权限
 *
 * @author 顾伟
 *         创建日期：13-4-8
 */
@Controller
@RequestMapping("/authentication")
public class AuthenticationController {
    @Autowired
    private Producer captchaProducer;

    @Autowired
    private IAuthenticationDao authenticationDao;

    /**
     * 生成验证码
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/image/code")
    public ModelAndView getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();

        response.setDateHeader("Expires", 0);
        //禁止浏览器缓存
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");

        response.setContentType("image/jpeg");
        // 创建图片验证码文本
        String capText = captchaProducer.createText();
        // 保存验证码文本到Session
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
        // 创建图片
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        // 输出图片数据
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
        return null;
    }

    /**
     * 修改密码是验证密码
     *
     * @param request
     * @return
     */
    @RequestMapping("/password/valid")
    @ResponseBody
    public String validPassword(HttpServletRequest request) {
        String password = ((CourseSystemUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getPassword();
        String confirmPassword = request.getParameter("old_pass");
        if (password.equals(confirmPassword)) {
            return "true";
        }
        return "false";
    }

    /**
     * 修改密码
     *
     * @param request
     * @return
     */
    @RequestMapping("/password/modify")
    @ResponseBody
    public boolean updatePassword(HttpServletRequest request) {
        String newPass = request.getParameter("new_pass");
        String userIdNo = ((CourseSystemUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUser().getUserIdNo();
        ((CourseSystemUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUser().setUserPassword(newPass);
        return authenticationDao.updatePasswordByUserId(userIdNo, newPass);
    }

    @RequestMapping("/{idNo}")
    @ResponseBody
    public CommonResult getUserPassword(@PathVariable String idNo) {
    	AuthenticationUser au = authenticationDao.getUserByUserName(idNo);
    	if (au == null) {
    		return new CommonResult("");
    	} else {
    		return new CommonResult(au.getUserPassword());
    	}
    }
}
